import FeedingApi from '../../../common/api/cbs/feeding.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { Select2Info, Select2Page } from "../../../common/serve-request.js";
import { locationService } from '../../../common/locationService.js';

let getEntryInfo = [], _pickerTime, _vm, attachesStr
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const curOrg = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;
    $(function () {
        _vm = new Vue({
            el: "#addsaleorders-form",
            data() {
                return {
                    breedBatch: {
                        id: "",
                        name: "",
                        curQty: "",
                        curDays: "",
                    },
                    fiOrg: {
                        id: "",
                        name: "",
                    },
                    farmOrg: {
                        id: "",
                        name: "",
                    },
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    remark: "",
                    entries: [],
                    uploadCount: 0,
                    attaches: [],
                    curQty: '',
                    curDays: '',
                    feedAmount: '',
                    feedStandards: '',
                    feedType: 'SAP-1',
                    breed: ''
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                let ids = Utils.GetSessionStorage("ids")
                if (params.id || ids) {
                    document.title = '饲喂记录 - 编辑'
                }
            },

        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        // _datetimePickerInit();
        clickFun()
        _initCommand()
        uploadInit();
    });


    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.attaches = _vm.attaches.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.attaches;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.attaches = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.attaches[i].id);
                    $(this).attr('data-image-id', _vm.attaches[i].imageId);
                    $(this).attr('data-url', _vm.attaches[i].url);
                    $(this).css({ 'background-image': `url(${_vm.attaches[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then(_res => {
                    _vm.attaches.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

    // 初始化数据
    const _initCommand = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });

        // 初始化 品种
        let type = await requestDict(DictionaryType.PIG_VARIETIES)
        let remedyDate = type.data;
        $('#breed').empty().select2({
            placeholder: '请选择猪只品种...', //默认文字提示
            language: "zh-CN", //汉化
            allowClear: true, //允许清空
            data: remedyDate.map(item => {
                return {
                    id: item.value,
                    text: item.displayName,
                }
            }),
        });
        let pigDefault = remedyDate.filter(item => {
            return item.isDefault == true
        })
        $(`#breed`).val(pigDefault[0]?.value).trigger("change")
        _vm.breed = pigDefault[0]?.value

        //选择品种
        $('#breed').on("select2:select", function () {
            _vm.breed = $('#breed').select2('data')[0]?.id
        });

        //获取养殖批次
        Select2Info($(`#breedBatch`), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/cur`, (params) => {
            return JSON.stringify({
                searchInfo: params.term,
                tags: ""
            })
        }, "POST", {
            allowClear: true,//允许清空
            placeholder: '请选择养殖批次...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}`;
            }
        });
        $('#breedBatch').setSelectValue();

        // 选择批次
        $('#breedBatch').on("select2:select", async function () {
            //查询存栏数
            let quantity = await FeedingApi.postBreedbatchsNum({ "id": $(this).val(), "bizDate": _vm.bizDate });
            //饲喂日龄=业务日期-存栏日期+1
            if (Utils.IsNotNull(quantity.firstDate)) {
                let firstDate = moment(new Date(quantity.firstDate)).format('YYYY-MM-DD');
                // let curDays = ((new Date(_vm.bizDate) - new Date(firstDate)) / (1000 * 60 * 60 * 24)) + 1;
                let curDays = ((new Date(_vm.bizDate.replace(/-/g, '/')) - new Date(firstDate.replace(/-/g, '/'))) / (1000 * 60 * 60 * 24)) + 1;
                getStandard(curDays, quantity.totalNum)
                _vm.curDays = curDays
            } else {
                _vm.curDays = 0
            }
            _vm.curQty = quantity?.totalNum
            let breedBatchInfo = $('#breedBatch').select2('data')[0]
            _vm.breedBatch.id = breedBatchInfo.id
            _vm.breedBatch.name = breedBatchInfo.name
            _vm.fiOrg.id = breedBatchInfo.fiOrgId
            _vm.fiOrg.name = breedBatchInfo.fiOrgName
            _vm.farmOrg.id = breedBatchInfo.farmOrgId
            _vm.farmOrg.name = breedBatchInfo.farmOrgName
        });

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            await FeedingApi.postFeedingInfo(ids).then(async res => {
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.entries.forEach((item, index) => item.seq = index)
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.entries))
                // 查询批次生产版本
                let param = {
                    searchInfo: res.breedBatch.name,
                    "isEnd": false,
                    "pageSize": 10,
                    "pageIndex": 0
                }
                let veridbreedbatchs = await FeedingApi.queryBreedbatchs(param)
                $('#veridbreedbatchs').val(veridbreedbatchs[0]?.verid)
                getStandard(res.breedBatch.curDays, res.breedBatch.curQty)
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        if (Utils.IsNotNull(getMainInfo)) {
            $('#fiOrg').setSelectValue(getMainInfo.fiOrg.id, getMainInfo.fiOrg.name);
            $('#breedBatch').setSelectValue(getMainInfo.breedBatch.id, getMainInfo.breedBatch.name);
            _vm.breedBatch = getMainInfo.breedBatch
            _vm.fiOrg = getMainInfo.fiOrg
            _vm.farmOrg = getMainInfo.farmOrg
            _vm.bizDate = getMainInfo.bizDate || moment(getMainInfo.bizFormObj?.bizDate).format('YYYY-MM-DD')
            _vm.remark = getMainInfo.remark
            _vm.feedAmount = getMainInfo.feedAmount
            _vm.feedStandards = getMainInfo.feedStandards
            _vm.feedType = getMainInfo.feedType
            _vm.breed = getMainInfo.breed
            _vm.curQty = getMainInfo.curQty || getMainInfo.breedBatch.curQty
            _vm.curDays = getMainInfo.curDays || getMainInfo.breedBatch.curDays
            $(`#breed`).val(_vm.breed).trigger("change")
            let editImage = []
            if (Utils.IsNotNull(getMainInfo.attaches) && !Utils.IsNotNull(ids)) {
                _images(getMainInfo.attaches)
                _vm.uploadCount = getMainInfo.uploadCount
            } else if (Utils.IsNotNull(getMainInfo.attaches)) {
                getMainInfo.attaches.split(',').forEach(item => {
                    editImage.push({
                        "imageId": item
                    })
                })
                _images(editImage)
                _vm.uploadCount = getMainInfo.attaches.split(',').length

            }
        }
        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        // 渲染 分录
        if (Utils.IsNotNull(getEntryInfo)) {
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
            let totalCount = 0, allresion = []
            getEntryInfo.map(item => {
                totalCount += Number(item.count)
                allresion.push(item.reasionName)
            })
            _vm.reasonNames = allresion.join(',')
            _vm.totalCount = totalCount
            _vm.totalWeight = Number(_vm.avgWeight) * Number(_vm.totalCount)
        }
        $('#avgWeight').on('change', function () {
            _vm.totalWeight = Number(_vm.avgWeight) * Number(_vm.totalCount)
        })
    }
    // 选择公司
    const selectfiOrg = async (farmInfo, breedBatchInfo) => {
        let fiOrgInfo = $('#fiOrg').select2('data')[0]
        _vm.fiOrg.id = fiOrgInfo.id
        _vm.fiOrg.name = fiOrgInfo.name
        let saleOrgsinfo = cutstr($('#select2-fiOrg-container').text(), 22)
        $('#select2-fiOrg-container').text(`${saleOrgsinfo}`)
        // await _initFarmOrg(fiOrgInfo.id, farmInfo, breedBatchInfo)
        _vm.farmOrg = { id: '', name: '' }
        // _vm.breedBatch = { id: "", name: "" }
        $(`#breedBatch`).empty()
    }
    // 选择服务部
    const selectfarm = (breedBatchInfo) => {
        let farmInfo = $('#farmOrg').select2('data')[0]
        _vm.farmOrg.id = farmInfo.id
        _vm.farmOrg.name = farmInfo.name
        // _vm.breedBatch = { id: "", name: "" }
        let saleOrgsinfo = cutstr($('#select2-farmOrg-container').text(), 22)
        $('#select2-farmOrg-container').text(`${saleOrgsinfo}`)
        // _initBreedBatch(farmInfo.id, breedBatchInfo);
    }
    // 获取饲喂标准
    const getStandard = (curDays, totalNum) => {
        let verid = $('#breedBatch').select2('data')[0]?.verid || $('#veridbreedbatchs').val()
        if (Utils.IsNotNull(verid)) {
            FeedingApi.getfeedStandards(curDays, verid).then(res => {
                let feedAmouts = Number(res.stdCount) * Number(totalNum)
                _vm.feedStandards = `${Utils.toThousands(feedAmouts, 2)} (${res.stdCount}kg/头)`
                _vm.feedAmount = feedAmouts
                _vm.feedType = res.feedType
            }, err => {
                $.toptip(err.responseJSON?.msg, 'error');
                _vm.feedStandards = ''
                _vm.feedAmount = ''
                _vm.feedType = DictionaryType.FEEDING_TYPE
            })
        }
        else {
            // toastr.warning('养殖批次不存在生产版本!')
            // return
        }
    }
    // 初始化农场
    const _initFarmOrg = (fiOrgId, json, breedBatchInfo) => {
        FeedingApi.queryComDepList(fiOrgId, 1).then(res => {
            let _outFarm = res.filter(s => s.parent.name == "猪场" || s.name.indexOf("服务部") != -1);
            $(`#farmOrg`).empty().select2({
                placeholder: `请选择服务部...`,//默认文字提示
                language: "zh-CN",//汉化
                allowClear: false,
                data: _outFarm.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            $(`#farmOrg`).setSelectValue()
            if (Utils.IsNotNull(json)) {
                $(`#farmOrg`).setSelectValue(json.id, json.name)
                // selectfarm(breedBatchInfo)
            }
        });
    }
    // 获取父级
    const getAllParend = (id, data) => {
        var res = [];    //定义一个数组用来存放找到的所有父级
        function dg(p) {
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                if (obj.oId == p) {
                    //将找到的父级元素放到res中
                    res.push(obj);
                    dg(obj.poId);
                }
            }
        }
        dg(id);
        return res;    //返回找到的数据
    }
    // 初始化批次
    const _initBreedBatch = (farmOrgId, json = '') => {
        Select2Page($(`#breedBatch`), FeedingApi.getBreedbatchs(), (params) => {
            return JSON.stringify({
                tags: '',
                farmOrgId: farmOrgId,
                fiOrgId: "",
                name: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            allowClear: false,//允许清空
            placeholder: `请选择养殖批次...`, //默认文字提示
            templateResult: function (res) {
                return `${res.name}`;
            }
        });
        $(`#breedBatch`).setSelectValue();
        if (json != '') {
            $(`#breedBatch`).setSelectValue(json.id, json.name)
        }
    }

    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
                _vm.bizDate = result.map(item => item.value).join('-');
                if (Utils.IsNotNull(_vm.breedBatch.id)) {
                    //查询存栏数
                    let quantity = await FeedingApi.postBreedbatchsNum({ "id": _vm.breedBatch.id, "bizDate": _vm.bizDate });
                    //饲喂日龄=业务日期-存栏日期+1
                    if (Utils.IsNotNull(quantity.firstDate)) {
                        let firstDate = moment(new Date(quantity.firstDate)).format('YYYY-MM-DD');
                        // let curDays = ((new Date(_vm.bizDate) - new Date(firstDate)) / (1000 * 60 * 60 * 24)) + 1;
                        let curDays = ((new Date(_vm.bizDate.replace(/-/g, '/')) - new Date(firstDate.replace(/-/g, '/'))) / (1000 * 60 * 60 * 24)) + 1;
                        getStandard(curDays, quantity.totalNum)
                        _vm.curDays = curDays
                    } else {
                        _vm.curDays = 0
                    }
                    _vm.curQty = quantity?.totalNum
                }
            }
        });// 默认配置
    }

    // 保存分录以上的内容
    const storeSession = () => {
        let _mainInfo = { ...{ breedBatch: _vm.breedBatch }, ...{ fiOrg: _vm.fiOrg }, ...{ farmOrg: _vm.farmOrg }, bizDate: _vm.bizDate, remark: _vm.remark, attaches: _vm.attaches, uploadCount: _vm.uploadCount, curQty: _vm.curQty, curDays: _vm.curDays, feedAmount: _vm.feedAmount, feedStandards: _vm.feedStandards, breed: _vm.breed, feedType: _vm.feedType };
        let deliverDatas = { ..._mainInfo };
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../feeding/feedinglist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 点击分录
        $('#add-saleEntry').on("click", function (e) {
            if (!Utils.IsNotNull(_vm.breedBatch?.id)) {
                $.toptip(`请先选择养殖批次!`, 'warning');
                return
            }
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0
            location.href = `../feeding/feedingentry.html?v=${Utils.GetTime()}&feedType=${_vm.feedType}&index=${index}&isEdit=${false}`;
        })

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))

            if (!Utils.IsNotNull(_vm.fiOrg.id)) {
                return $.toptip(`请选择公司!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.farmOrg.id)) {
                return $.toptip(`请选择服务部!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.breedBatch.id)) {
                return $.toptip(`请选择养殖批次!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.breed)) {
                return $.toptip(`请选择猪只品种!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加饲喂记录分录信息!`, 'warning');
            }
            if (_vm.curQty == 0) {
                return $.toptip('该批次存栏数量为0,无法做饲喂记录！', 'error')
            }
            savetips();
        })

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            // 过滤
                            let datas = getEntryInfo.filter(item => item.seq != seq)
                            // 重置seq
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []

                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))
                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            let totalCount = 0, allresion = []
                            info.map(item => {
                                totalCount += Number(item.count)
                                allresion.push(item.reasionName)
                            })
                            _vm.reasonNames = allresion.join(',')
                            _vm.totalCount = totalCount
                            _vm.totalWeight = Number(_vm.avgWeight) * Number(totalCount)
                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../feeding/feedingentry.html?v=${Utils.GetTime()}&feedType=${_vm.feedType}&index=${index}&isEdit=${true}`;
        });
    }
    // 保存
    const savetips = () => {
        let sumCount = 0
        getEntryInfo.forEach(item => {
            sumCount += Number(item.feedingCount)
        })
        let tiptext = '是否确认保存该饲喂记录？'
        if (Utils.IsNotNull(_vm.feedAmount) && Number(sumCount) > Number(_vm.feedAmount)) {
            tiptext = '饲喂量大于标准量，是否确认保存该饲喂记录？'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >${tiptext}</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage("ids")
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))

                        let imageArr = []
                        _vm.attaches.forEach(item => {
                            imageArr.push(item.imageId)
                        })
                        let attachesStr = imageArr.join(',')

                        let datas = {
                            ...{ breedBatch: _vm.breedBatch }, ...{ fiOrg: _vm.fiOrg }, ...{ farmOrg: _vm.farmOrg }, bizDate: _vm.bizDate, remark: _vm.remark, feedAmount: _vm.feedAmount, entries: [...entries], attaches: attachesStr, breed: _vm.breed
                        };
                        datas.breedBatch.curQty = _vm.curQty
                        datas.breedBatch.curDays = _vm.curDays || 0
                        if (Utils.IsNotNull(ids)) {
                            return FeedingApi.putUpFeeding(ids, JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `../feeding/feedinglist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            })
                        }
                        else {
                            FeedingApi.postAddFeeding(JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    location.href = `../feeding/feedinglist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)